from StormCounter import StormCounter, get_cursor
from MeanFrequencyDistribution import MFD
import csv, datetime




def process_storm(ts, start, end, mfd_src):
    """process a storm giving the database and a time period
    ts: definition of the time series, now only support pyodbc
    """
    table = ts['table']
    time_fld = ts['fields']['time']
    value_fld = ts['fields']['value']
    weather_fld = ts['fields']['weather']
    sql = 'select [%s], [%s] from %s where [%s] > 0 and  [%s]>=%s and  [%s]<=%s order by [%s] ' % (time_fld, value_fld, table, value_fld, time_fld, start.strftime('#%m/%d/%Y %H:%M#'), time_fld, end.strftime('#%m/%d/%Y %H:%M#'), time_fld)
    
    ts_list = []
    for r in get_cursor(ts['db'], ts['password']).execute(sql):
        ts_list.append((getattr(r, time_fld), getattr(r, value_fld)))
    
    mfd = MFD(mfd_src)
    ts = {'ts': ts_list, 'timestep': datetime.timedelta(minutes=5)}

    return mfd.rainfallStat(ts)


#data stored in a mdb file
import sys, os

root = os.path.dirname(sys.argv[0]).replace('src', '')
#db = r'C:\dropbox\My Dropbox\projects\pystorm\data\rainfall.mdb'
db = os.path.join(root, 'data', 'rainfall.mdb')
password = ''
ts = {'db': db, 'password': password, 'table': 'mkii', 'fields': {'time': 'time', 'value': 'rainfall', 'weather': 'weather'}, 'timestep': datetime.timedelta(minutes=5)}
#mdf_src = r'C:\dropbox\My Dropbox\projects\pystorm\data\Sectional_mean_frequency_distribution_for_storm.csv'
mdf_src = os.path.join(root, 'data', 'Sectional_mean_frequency_distribution_for_storm.csv')
rain_def = {'max_duration': datetime.timedelta(days=1), 'min_total': 0.1, 'timestep': datetime.timedelta(minutes=5)}
storms = StormCounter(ts, rain_def).count()
mdf = MFD(mdf_src)

#write the csv file

#f = open(r'M:\proj\0921\6002\0004 Private Source I&I Investigations\WIBs\Rain Data\storms2.csv', 'w')
f = open(os.path.join(root, 'data', 'storms.csv'), 'w')
writer = csv.writer(f, lineterminator='\n')
writer.writerow(['from', 'to', 'total', 'duration', 'dry_days_before', 'peak_freq', 'peak_duration', 'volume_freq', 'volume_duration'] )

previous_storm = None
for x in storms:
    
    stats = process_storm(ts, x['start'], x['end'], mdf_src)
    
    fs1 = []
    return_results = {}
    peak = {}
    volume = {}
    counter = 0
    for y in stats['summary']:
        fq = mdf.getFrequency(y['frequency'],y['rainfall'])
        fs1.append ('%s %s (%s)' % (y['rainfall'], y['frequency'], fq))
        
        if counter<2:
            if volume:
                vfq =  volume['frequency']
                if mdf.frequencies.index(fq)> mdf.frequencies.index(vfq):
                    volume = {'duration': y['frequency'], 'frequency': fq, 'total': y['rainfall']}
            else:
                volume = {'duration': y['frequency'], 'frequency': fq, 'total': y['rainfall']}
            
        if peak:
            vfq =  peak['frequency']
            if mdf.frequencies.index(fq)>= mdf.frequencies.index(vfq):
                peak = {'duration': y['frequency'], 'frequency': fq, 'total': y['rainfall']}
        else:
            peak = {'duration': y['frequency'], 'frequency': fq, 'total': y['rainfall']} 
        counter+=1
        return_results[fq] = y['frequency']
        
#        fs.append (fq)
#    flist = mdf.frequencies
#    idx = max([flist.index(z) for z in fs])
#   
#    max_frequency = flist[idx]
#    max_duration = return_results[max_frequency]
#    max_frequency = flist[idx]
    dry_days_before = 'NA'
    if previous_storm:
        dry_days_before = x['start'] - previous_storm['end']
        dry_days_before = dry_days_before.days + dry_days_before.seconds/60.0/60/24
    
    writer.writerow([x['start'].strftime('#%m/%d/%Y %H:%M#'), x['end'].strftime('#%m/%d/%Y %H:%M#'), x['total'], (x['end'] - x['start']+ ts['timestep']).days*24 + (x['end'] - x['start']+ ts['timestep']).seconds/60.0/60.0, dry_days_before] + [peak['frequency'], peak['duration'], volume['frequency'], volume['duration']] + fs1)    
    previous_storm = x.copy()

f.close()

